#include"SList.h"
void SLprint(SLTNode* phead)
{
	SLTNode* pcur = phead;
	
	while (pcur)
	{
		printf("%d -> ", pcur->data);
		pcur = pcur->next;
	}
	printf("NULL\n");
}
SLTNode* SLBuyNode(SLTDataType x)
{
	SLTNode* node = (SLTNode*)malloc(sizeof(SLTNode));
	if (node == NULL)
	{
		perror("melloc fail\n");
		exit(1);
	}
	node->data = x;
	node->next = NULL;
	return node;
}
void* SLPushBack(SLTNode** pphead, SLTDataType x)
{
	assert(pphead);
	SLTNode* newnode = SLBuyNode(x);
	if (*pphead == NULL)
	{
		*pphead = newnode;
	}
	else
	{
	SLTNode* newnode = SLBuyNode(x);
		SLTNode* pur = *pphead;
		while (pur->next)
		{
			pur = pur->next;
		}
		pur->next = newnode;
	}
}
void* SLPushFront(SLTNode** pphead, SLTDataType x)
{
	assert(pphead);
	SLTNode* newnode = SLBuyNode(x);
	newnode->next = *pphead;
	*pphead = newnode;
}
void* SLPopBack(SLTNode** pphead)
{
	assert(pphead && *pphead);
	if ((*pphead)->next == NULL)
	{
		free(*pphead);
		*pphead = NULL;	
	}
	else
	{
		SLTNode* pur = *pphead;
		SLTNode* prev = NULL;
		while (pur->next)
		{
			prev = pur;
			pur = pur->next;
		}
		free(pur);
		pur = NULL;
		prev->next = NULL;
	}

}
void* SLPopFront(SLTNode** pphead)
{
	assert(pphead && *pphead);
	SLTNode* pur = (*pphead)->next;
			free(*pphead);
			*pphead = pur;	
}
SLTNode* SLFind(SLTNode** pphead,SLTDataType x)
{
	assert(*pphead);
	SLTNode* pcur = *pphead;
	while (pcur)
	{
		if (pcur->data == x)
		{
			return pcur;
		}
		pcur = pcur->next;
	}
	return NULL;
}
void SLTnsert(SLTNode** pphead, SLTNode* pos, SLTDataType x)
{
	assert(pphead && pos);
	if (*pphead == pos)
	{
		SLPushFront(pphead, x);
	}
	SLTNode* pcur = *pphead;
    SLTNode* Newnode = SLBuyNode(x);
	while (pcur->next != pos)
	{
		pcur = pcur->next;
	}
	pcur->next = Newnode;
	Newnode->next = pos;
	
}
void SLInsertAfter(SLTNode* pos, SLTDataType x)
{
	assert(pos);
    SLTNode* newnode = SLBuyNode(x);
	newnode->next = pos->next;
	pos->next = newnode;
}
void SLTErase(SLTNode** pphead, SLTNode* pos)
{
	assert(pphead && pos);
	if (*pphead == pos)
	{
		SLPopFront(pphead);
	}
	else {
		SLTNode* pcur = *pphead;
		while (pcur->next != pos)
		{
			pcur = pcur->next;
		}
		pcur->next = pos->next;
		free(pos);
		pos = NULL;
	}
}
void SLTEraseFront(SLTNode* pos)
{
	assert(pos && pos->next);
	SLTNode* prev = pos->next;
	pos->next = prev->next;
	free(prev);
	prev = NULL;

}
void SListDestory(SLTNode** phead)
{
	SLTNode* pcur = *phead;
	while (pcur)
	{
		SLTNode* new = pcur->next;
		free(pcur);
		pcur = new;
	}
	*phead = NULL;
}
